package com.autonavi.yunda.yunji.core.engine.argresolver;

import com.autonavi.yunda.yunji.common.exception.AmapException;
import com.autonavi.yunda.yunji.common.exception.AmapExceptionCode;
import com.autonavi.yunda.yunji.common.utils.JsonUtils;
import com.autonavi.yunda.yunji.core.vo.HttpRequest;
import com.autonavi.yunda.yunji.core.vo.param.Param;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cizhong.wcs
 * @date 2022/6/1 20:36
 */
@Component
public class RequestArgsResolverComposite implements ParamResolver {
    private final List<ParamResolver> argumentResolvers = new ArrayList<>();

    public RequestArgsResolverComposite() {
        addResolver(new BodyParamResolver());
        addResolver(new HeaderParamResolver());
        //必须为最后一个,如果都不支持则都是用urlParamResolver
        addResolver(new UrlParamResolver());
    }

    @Override
    public boolean supportsParam(Param param) {
        return true;
    }

    @Override
    public Object resolve(HttpRequest request, Param param) {
        ParamResolver resolver = getArgumentResolver(param);
        if (resolver == null) {
            throw new AmapException(AmapExceptionCode.COMMON_ILLEGAL_PARAM, "not find support resolver param:" + JsonUtils.toString(param));
        }
        return resolver.resolve(request, param);
    }

    public RequestArgsResolverComposite addResolver(ParamResolver resolver) {
        this.argumentResolvers.add(resolver);
        return this;
    }

    private ParamResolver getArgumentResolver(Param param) {
        for (ParamResolver resolver : this.argumentResolvers) {
            if (resolver.supportsParam(param)) {
                return resolver;
            }
        }
        return null;
    }
}
